package com.M.book.service;

import com.M.book.dao.BookDao;
import com.M.book.enums.BookStatusEnum;
import com.M.book.mapper.BookInfoMapper;
import com.M.book.model.BookInfo;
import com.M.book.model.PageRequest;
import com.M.book.model.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class BookService {
//    private BookDao bookDao = new BookDao();

//    @Autowired
//    private BookDao bookDao;
    @Autowired
    private BookInfoMapper bookInfoMapper;

//    public List<BookInfo> getBookList() {
//        List<BookInfo> bookInfos = bookDao.mockData();
//        for(BookInfo bookInfo : bookInfos) {
//            if(bookInfo.getStatus() == 1){
//                bookInfo.setStatusCN("可借阅");
//            }else {
//                bookInfo.setStatusCN("不可借阅");
//            }
//        }
//
//        return bookInfos;
//    }
    public PageResult<BookInfo> selectBookInfoByPage(PageRequest pageRequest) {
        if(pageRequest == null) {
            return null;
        }
        //获取总记录数
        Integer count = bookInfoMapper.count();
        //获取当前记录
//        log.info(pageRequest.toString());
//        log.info(pageRequest.getOffset().toString());
        List<BookInfo> bookInfos = bookInfoMapper.selectBookInfoByPage(0, 10);
        if(bookInfos != null || !bookInfos.isEmpty()) {
            for(BookInfo bookInfo : bookInfos) {
                bookInfo.setStatusCN(BookStatusEnum.getNameByCode(bookInfo.getStatus()).getName());
            }
        }
        return new PageResult<>(bookInfos, count, pageRequest);
    }

    /**
     * 添加图书
     * @param bookInfo
     * @return
     */
    public Integer addBook(BookInfo bookInfo) {
        Integer result = 0;
        try{
            result = bookInfoMapper.insertBook(bookInfo);
        } catch(Exception e){
            log.error("添加图书失败, e:" + e.getMessage());
        }

        return result;
    }

    public BookInfo queryBookInfoById(Integer id) {
        return bookInfoMapper.queryBookInfoById(id);
    }

    /**
     * 更新图书
     * @param bookInfo
     * @return
     */
    public Integer updateBook(BookInfo bookInfo) {
        Integer result = 0;
        try{
            result = bookInfoMapper.updateBook(bookInfo);
        } catch(Exception e){
            log.error("更新图书失败" + e.getMessage());
        }

        return result;
    }

    public Integer batchDelete(List<Integer> ids) {
        Integer result = 0;
        try {
            result = bookInfoMapper.batchDelete(ids);
        } catch (Exception e) {
            log.error("批量删除图书失败" + e.getMessage());
        }
        return result;
    }
}
